//
//  LXCWApplyViewController.m
//  ZuLinProject
//
//  Created by bancheng on 2021/12/24.
//  Copyright © 2021 LX_App. All rights reserved.
//

#import "LXCWApplyViewController.h"
#import "LXTableViewCell.h"
#import "LXRemarkTabelViewCell.h"
#import "LXApplyAnnexTableCell.h"
#import "LXChooseManagerViewController.h"
#import "FuZeRenModel.h"
#import "LXAnnexShowTableViewCell.h"
@interface LXCWApplyViewController()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic) UITableView *tableView;
@property (nonatomic) NSArray *data;
@property (nonatomic) NSMutableDictionary *loanDic;
@property (nonatomic) NSDictionary *selDic;
@property (nonatomic) NSMutableArray *annexAry;
@property (nonatomic) NSMutableArray *annexDataAry;
@property (nonatomic) NSString *fundTypeStr;
// 0 未结清 1已结清
@property (nonatomic) NSInteger settleState;

@property (nonatomic) FuZeRenModel *fuzeModel;
@property (nonatomic) NSString *manageId;

@end

@implementation LXCWApplyViewController
- (void)viewDidLoad {
    [super viewDidLoad];

    
    if (self.statisticsType == 1) {
        self.fundTypeStr = [NSString getCollectionNameWithFundType:self.model.fundType];
        [self layoutCustomNav:self.view title:[NSString stringWithFormat:@"%@记录",self.fundTypeStr]];
    }
    else{
        self.fundTypeStr = [NSString getPaidNameWithFundType:self.model.fundType];

        [self layoutCustomNav:self.view title:[NSString stringWithFormat:@"%@记录",self.fundTypeStr]];
    }
    
    NSDictionary *dic = @{
        @"url":@"upLoad_B",
    };
    self.annexAry = [NSMutableArray array];
    self.annexDataAry = [NSMutableArray array];
    [self.annexAry addObject:dic];
    
    [self.tableView registerClass:[LXTableViewCell class] forCellReuseIdentifier:NSStringFromClass([LXTableViewCell class])];
    [self.tableView registerClass:[LXApplyAnnexTableCell class]
         forCellReuseIdentifier:NSStringFromClass([LXApplyAnnexTableCell class])];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXRemarkTabelViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([LXRemarkTabelViewCell class])];
    [self.tableView registerClass:[LXAnnexShowTableViewCell class] forCellReuseIdentifier:NSStringFromClass([LXAnnexShowTableViewCell class])];

    
    
    
    self.view.backgroundColor = White_Color;
    [self.view addSubview:self.tableView];
    
    [self loadData];
    
    [self setBottomViewWithText:@"确认新增"];

    
}
- (void)loadData{
    
    self.loanDic  = [NSMutableDictionary dictionary];
    
    
    
    
    self.settleState = self.model.settleState;
    
    // 车牌号
    [self.loanDic setValue:!StringIsEmpty(self.model.carNumber)?self.model.carNumber:self.model.carNum forKey:@"carNum"];
    [self.loanDic setValue:[NSString stringWithFormat:@"%@ %@",self.model.carBrand,self.model.carMode] forKey:@"carBrand"];
 
  

    
    if (self.statisticsType == 1) {
        
        [self.loanDic setValue:@"未结清" forKey:@"settleState"];
        
        // 客户姓名
        if (!StringIsEmpty(self.model.payerName)) {
            [self.loanDic setValue:self.model.payerName forKey:@"customerName"];
        }
        else {
            [self.loanDic setValue:self.model.customerName forKey:@"customerName"];
        }
        
        // 应收日期
        [self.loanDic setValue:self.model.exceptReceiveDate forKey:@"date"];
        // 应收金额
        [self.loanDic setValue:self.model.amount forKey:@"amount"];
        if (self.type==1) {
            // 实收日期
//            [self.loanDic setValue:self.model.receiveDate forKey:@"actualDate"];
            // 实收金额
//            [self.loanDic setValue:self.model.receiveAmount forKey:@"actualAmount"];
            // 已收金额
            [self.loanDic setValue:self.model.receiveAmount forKey:@"Yamount"];
            // 付款人
            [self.loanDic setValue:self.model.receiveEmployeeName forKey:@"manageName"];
            self.manageId = self.model.receiveEmployeeId;
        }
        
        // 应收类型
        NSString *fundType = [NSString getCollectionNameWithFundType:self.model.fundType];
        [self.loanDic setValue:fundType forKey:@"fundType"];
    }
    else {
        // 客户姓名
        if (!StringIsEmpty(self.model.payeeName)) {
            [self.loanDic setValue:self.model.payeeName forKey:@"customerName"];
        }
        else {
            [self.loanDic setValue:self.model.customerName forKey:@"customerName"];
        }
        
        [self.loanDic setValue:@"未付清" forKey:@"settleState"];
        
        // 应付日期
        [self.loanDic setValue:self.model.exceptPaidDate forKey:@"date"];
        // 应付金额
        [self.loanDic setValue:self.model.amount forKey:@"amount"];
        if (self.type== 1) {
            // 实付日期
//            [self.loanDic setValue:self.model.paidDate forKey:@"actualDate"];
            // 实付金额
//            [self.loanDic setValue:self.model.paidAmount forKey:@"actualAmount"];
            // 已付金额
            [self.loanDic setValue:self.model.paidAmount forKey:@"Yamount"];
            
            // 付款人
            [self.loanDic setValue:self.model.payEmployeeName forKey:@"manageName"];
            self.manageId = self.model.payEmployeeId;
        }
        // 应付类型
        NSString *fundType = [NSString getPaidNameWithFundType:self.model.fundType];
        [self.loanDic setValue:fundType forKey:@"fundType"];
        
    }
    
    
    if (self.type== 1) {
        [self.loanDic setValue:self.model.remark forKey:@"remark"];
        
        for (NSString *url in self.model.pics) {
            NSString *imageUrl = [NSString stringWithFormat:@"%@%@",HTTP_URL,url];
            [self.annexAry insertObject:@{@"url":imageUrl} atIndex:0];
            [self.annexDataAry insertObject:imageUrl atIndex:0];
        }
    
    }
        
            

    self.data = @[
         
           @{
               @"title":@"车牌号",
               @"key":@"carNum",
               @"height":@(kComHeight)
           },
           @{
               @"title":@"品牌型号",
               @"key":@"carBrand",
               @"height":@(kComHeight)
           },
           @{
               @"title":self.statisticsType==1?(self.model.payerType==0?@"客户姓名":@"合作伙伴"):((self.model.payeeType==0?@"客户姓名":@"合作伙伴")),
               @"key":@"customerName",
               @"height":@(kComHeight),
           },
           @{
               @"title":self.statisticsType==1?@"收款类型":@"付款类型",
               @"key":@"fundType",
               @"height":@(kComHeight),
           },
           @{
               @"title":self.statisticsType==1?@"应收日期":@"应付日期",
               @"key":@"date",
               @"height":@(kComHeight),
           },
           @{
               @"title":self.statisticsType==1?@"应收金额(元)":@"应付金额(元)",
               @"key":@"amount",
               @"height":@(kComHeight),
           },
           @{
               @"title":self.statisticsType==1?@"已收金额(元)":@"已付金额(元)",
               @"key":@"Yamount",
               @"height":[self.loanDic[@"Yamount"] doubleValue]>0?@(kComHeight):@(0.0001),
           },
           @{
               @"title":self.statisticsType==1?@"*实收日期":@"*实付日期",
               @"key":@"actualDate",
               @"placeHolder":self.statisticsType==1?@"请选择实收日期":@"请选择实付日期",
               @"sel":@"clickDateAction",
               @"showAccess":@(YES),
               @"canEdit":@(NO),
               @"height":@(kComHeight),
           },
           @{
               @"title":self.statisticsType==1?@"*实收金额(元)":@"*实付金额(元)",
               @"key":@"actualAmount",
               @"placeHolder":self.statisticsType==1?@"请输入实收金额":@"请输入实付金额",
               @"inputType":@(NUM_DECIMAL),
               @"keyboardType":@(UIKeyboardTypeDecimalPad),
               @"maxLength":@(7),
               @"canEdit":@(YES),
               @"height":@(kComHeight),
           },
           @{
               @"title":@"*状态",
               @"key":@"settleState",
               @"placeHolder" : @"请选择状态",
               @"canEdit":@(NO),
               @"showAccess":@(YES),
               @"sel":@"clickSettleStateAction",
               @"height":@(kComHeight),
           },
           @{
               @"title":self.statisticsType==1?@"*收款人":@"*付款人",
               @"key":@"manageName",
               @"placeHolder" : self.statisticsType==1?@"请选择收款人":@"请选择付款人",
               @"canEdit":@(NO),
               @"showAccess":@(YES),
               @"sel":@"clickManageAction",
               @"height":@(kComHeight),
           },
           @{
               @"title":[NSString stringWithFormat:@"%@照片(最多4张)",self.fundTypeStr],
               @"key":@"annex",
               @"height":@(kComAnnexHeight)
           },
           @{
               @"title":@"备注",
               @"key":@"remark",
               @"height":@(150)
           }
    ];
    

    
    
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.data count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.data[indexPath.row];
    if ([dic[@"key"] isEqualToString:@"annex"]) {
        return [LXApplyAnnexTableCell getCellHeightWithDataSource:self.annexAry] + 30;
    }
    return [dic[@"height"] doubleValue];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSDictionary *dic = self.data[indexPath.row];
     if ([dic[@"key"] isEqualToString:@"annex"]) {
        LXApplyAnnexTableCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXApplyAnnexTableCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setClipsToBounds:YES];
        cell.titleLab.text = dic[@"title"];
        [cell reloadAnnexData:self.annexAry WithMaxNum:4];
        
        
        // 添加图片
        [cell setCallBackTakeAnnex:^(NSInteger num) {
            
            [[LXPhotoHelper shareHelper] showImageViewSelcteWithResultBlock:^(id data) {
                
                [self uploadImage:data];
                
            } andMultipleImageBlock:^(id data) {
                
                [self uploadImage:data];
                
            } andSelectedNum:4 - self.annexDataAry.count];
            
        }];
        
        
        // 放大图片
        [cell setCallBackExtendAnnex:^(NSInteger num,id obj) {
            LXBigImageView *view = [[LXBigImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) WithShowImageAry:self.annexDataAry];
            [view.scrollView setContentOffset:CGPointMake(ScreenWidth*num, 0) animated:NO];
            [[UIApplication sharedApplication].delegate.window addSubview:view];
            
        }];
        // 删除图片
        [cell setCallBackDeleteAnnex:^(NSInteger num) {
            
            [self.annexAry removeObjectAtIndex:num];
            [self.annexDataAry removeObjectAtIndex:num];

            [self.tableView reloadData];
        }];
        
        
        return cell;
    }
    
   else if([dic[@"key"]  isEqualToString:@"remark"]){
        // 备注
        LXRemarkTabelViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXRemarkTabelViewCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setClipsToBounds:YES];
        cell.textView.placeholder = @"请输入备注...";
        cell.textView.maxLength = 200;
        cell.remarkTitle.text = @"备注";
        cell.textView.text = self.loanDic[@"remark"];
        [cell setTextViewEdit:^(NSString * _Nonnull textStr) {
            [self.loanDic setValue:textStr forKey:@"remark"];
        }];
        return cell;
    }

    
    
    LXTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXTableViewCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setClipsToBounds:YES];
    

    cell.cellDic = dic;
    cell.textFiled.hidden = NO;
    cell.subTitleLab.hidden = YES;
    cell.textFiled.text = self.loanDic[dic[@"key"]];
    
    cell.textfiledDidChangeBlock = ^(NSString * _Nonnull textStr) {
        if ([dic[@"key"] isEqualToString:@"actualAmount"]) {
            
            if ([textStr doubleValue] == [self.model.amount doubleValue]) {
                self.settleState = 1;
                if (self.statisticsType == 1) {
                    self.loanDic[@"settleState"] = @"已结清";
                }
                else {
                    self.loanDic[@"settleState"] = @"已付清";
                }
               
            }
            else {
                self.settleState = 0;
                if (self.statisticsType == 1) {
                    self.loanDic[@"settleState"] = @"未结清";

                }
                else {
                    self.loanDic[@"settleState"] = @"未付清";
                }
                
                
            }
            
            [self.tableView reloadData];
            
        }
    };
    cell.textfiledChangeBlock = ^(NSString * _Nonnull textStr) {
        self.loanDic[dic[@"key"]]  = textStr;
    };
    
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *dic = self.data[indexPath.row];
    self.selDic = dic;
    NSString * selName = dic[@"sel"];
    SEL action = NSSelectorFromString(selName);
    if ([self respondsToSelector:action]) {
        [self performSelector:action withObject:nil afterDelay:0];
    }

}




#pragma mark -- 选择实付实收日期
-(void)clickDateAction{
    [self.view endEditing:YES];
    DatePickView *datePicker =[[DatePickView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withDateStr:self.loanDic[@"actualDate"] withIsMaxDate:YES withNoForward:NO WithTips:@"请选择"] ;
    [datePicker showBoomView];
    [[[UIApplication sharedApplication].delegate window] addSubview:datePicker];
    WEAKSELF
    datePicker.block = ^(NSString *yearString){
        
//        if([NSString compareDate:self.loanDic[@"date"] withDate:yearString withFormat:k_DateFormat]==-1){
//
//            if (self.statisticsType == 1) {
//                showAlert(@"实收日期不能小于应收日期");
//            }
//            else {
//                showAlert(@"实付日期不能小于应付日期");
//            }
//
//        }
//        else {
            [self.loanDic setObject:yearString forKey:weakSelf.selDic[@"key"]];
            [weakSelf.tableView reloadData];
//        }
    };
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kViewTopHeight, ScreenWidth, kScreenHeight - kViewTopHeight - kComHeight - 10) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = ColorWithF7F8FA;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}




#pragma mark ---- 确认新增/修改点击事件
- (void)clickBottomView:(UIButton *)sender{
    
    
    
    if (self.statisticsType == 1) {
        if (StringIsEmpty(self.loanDic[@"actualDate"])) {
            showAlert(@"请选择实收日期");
            return;
        }
        if (StringIsEmpty(self.loanDic[@"actualAmount"])) {
            showAlert(@"请选择实收金额");
            return;
        }
        if ([self.loanDic[@"actualAmount"] doubleValue] == 0) {
            showAlert(@"实收金额不能为0");
            return;
        }
        if (StringIsEmpty(self.loanDic[@"manageName"])) {
            showAlert(@"请选择收款人");
            return;
        }
        
        
    }
    else {
        if (StringIsEmpty(self.loanDic[@"actualDate"])) {
            showAlert(@"请选择实付日期");
            return;
        }
        if (StringIsEmpty(self.loanDic[@"actualAmount"])) {
            showAlert(@"请选择实付金额");
            return;
        }
        if ([self.loanDic[@"actualAmount"] doubleValue] == 0) {
            showAlert(@"实付金额不能为0");
            return;
        }
        if (StringIsEmpty(self.loanDic[@"manageName"])) {
            showAlert(@"请选择付款人");
            return;
        }
    }
   

   
    
    [Tool showAlertTitle:@"是否确认提交" msg:nil cancelTitle:@"取消" commitBtnTitle:@"确定" cancelHandlerBlock:^{
    } commitHandlerBlock:^{
        
        

        NSDictionary *dic;
        NSString *url;
        //收款
        if (self.statisticsType == 1) {
            
            dic = @{
                
                @"id":self.model.ID, // 数据id
                @"receiveAmount":self.loanDic[@"actualAmount"],// 实收金额
                @"receiveDate":self.loanDic[@"actualDate"],// 实收日期
                @"settleState":@(self.settleState), // 状态
                @"receiveEmployeeName":self.loanDic[@"manageName"], // 收款人
                @"receiveEmployeeId":self.manageId, //   收款人id
                @"pics":self.annexDataAry, //  图片
                @"remark":self.loanDic[@"remark"], //  备注
            };
            
            url = POST_UpdateTmoneyintoflow;
        }
        else {
            dic = @{
                
                @"id":self.model.ID, // 数据id
                @"paidAmount":self.loanDic[@"actualAmount"],// 实收金额
                @"paidDate":self.loanDic[@"actualDate"],// 实收日期
                @"settleState":@(self.settleState), // 状态
                @"payEmployeeId":self.manageId,// 收款人id
                @"payEmployeeName":self.loanDic[@"manageName"], //   收款人
                @"pics":self.annexDataAry, //  图片
                @"remark":self.loanDic[@"remark"], //  备注
            };
            
            url = POST_UpdateTmoneyoutflow;
        }
        
        
        
        [MSNetworkManager postRevertUrl:url params:dic success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
            
            if (isSuccess) {
            
                showAlert(@"提交成功");
                
                kUserDefaultSetBool(YES, kRefreshStr);
                [self.navigationController popViewControllerAnimated:YES];
            }
            
        } failure:^(NSUInteger code, NSString * _Nonnull message) {
        } withShowHud:YES];
    } onVC:self];
    
 
}


-(void)uploadImage:(NSArray *)ary{
    
    [self.annexAry removeLastObject];
    
    MBProgressHUD *hud = [MBProgressHUD showGif];
        
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        
    dispatch_async(queue, ^{
    
    [ary enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    
        [MSNetworkManager postRevertUrl:POST_UploadFile_URL params:@{@"type":@"1"} formData:@[obj] success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
            if (isSuccess) {
                
                NSString *imageUrl = [NSString stringWithFormat:@"%@%@",HTTP_URL,resonseObj[@"url"]];

                [self.annexAry addObject:@{
                    @"url":imageUrl
                }];
                [self.annexDataAry addObject:resonseObj[@"url"]];
                
                if (idx == ary.count-1) {
                    [hud hide];
                    [self.annexAry addObject:@{
                        @"url":@"upLoad_B",
                    }];
                    [self.tableView reloadData];
                }
                dispatch_semaphore_signal(semaphore);
            }
        } failure:^(NSUInteger code, NSString * _Nonnull message) {
            dispatch_semaphore_signal(semaphore);
            [hud hide];
        } withShowHud:NO];
        
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        
        
     }];
    });

}
-(void)clickSettleStateAction{
    [self.view endEditing:YES];
    
    
    if (self.statisticsType == 1) {
        [Tool showSheetTitle:nil msg:nil cancelTitle:@"取消" oneBtnTitle:@"已结清" twoBtnTitle:@"未结清" cancelHandlerBlock:^{
        } oneHandlerBlock:^{
            self.settleState = 1;
            [self.loanDic setValue:@"已结清" forKey:@"settleState"];
            [self.tableView reloadData];
        } twoHandlerBlock:^{
            self.settleState = 0;
            [self.loanDic setValue:@"未结清" forKey:@"settleState"];
            [self.tableView reloadData];
        } onVC:self];
    }
    else {
        [Tool showSheetTitle:nil msg:nil cancelTitle:@"取消" oneBtnTitle:@"已付清" twoBtnTitle:@"未付清" cancelHandlerBlock:^{
        } oneHandlerBlock:^{
            self.settleState = 1;
            [self.loanDic setValue:@"已付清" forKey:@"settleState"];
            [self.tableView reloadData];
        } twoHandlerBlock:^{
            self.settleState = 0;
            [self.loanDic setValue:@"未付清" forKey:@"settleState"];
            [self.tableView reloadData];
        } onVC:self];
    }
    
   
    
    
}

//MARK: 付款收款人
-(void)clickManageAction{
    
    [self.view endEditing:YES];
    
    
    LXChooseManagerViewController *vc = [[LXChooseManagerViewController alloc] init];
    WEAKSELF
    [vc setToSendValue:^(FuZeRenModel * _Nonnull model) {
        [weakSelf.loanDic setValue:model.realName forKey:@"manageName"];
        weakSelf.manageId = model.ID;
        weakSelf.fuzeModel = model;
        [weakSelf.tableView reloadData];
    }];
    vc.model = self.fuzeModel;
    [self pushToNextController:vc];
    
    
    
}
@end
